package com.corpdata.app.contract.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.corpdata.app.contract.dao.ContractInfoMapper;
import com.corpdata.app.contract.entity.ContractInfo;
import com.corpdata.app.contract.entity.ContractPartition;
import com.corpdata.app.contract.entity.ContractReceivable;
import com.corpdata.app.contract.service.ContractInfoService;
import com.corpdata.app.contract.service.ContractPartitionService;
import com.corpdata.app.contract.service.ContractReceivableService;
import com.corpdata.app.contract.service.ContractStationService;
import com.corpdata.app.customer.entity.CustomerTeam;
import com.corpdata.app.customer.service.CustomerTeamService;
import com.corpdata.app.finance.entity.FinancialSetting;
import com.corpdata.app.finance.service.FinancialSettingService;
import com.corpdata.app.message.entity.SysMessage;
import com.corpdata.app.message.entity.SysMessageUser;
import com.corpdata.app.message.service.SysMessageService;
import com.corpdata.app.project.entity.ProjectStation;
import com.corpdata.app.project.service.ProjectStationService;
import com.corpdata.common.result.Result;
import com.corpdata.common.upload.service.SysAttachmentService;
import com.corpdata.common.utils.CorpdataUtil;
import com.corpdata.core.base.AbstractBaseService;
import com.corpdata.system.log.OptLog;
import com.corpdata.system.log.OptLogConstant;
import com.corpdata.system.security.shiro.util.UserUtil;

/**
 * 合同表
 * 
 * @author wu
 * @email 64088839@qq.com
 * @date 2018-07-02 16:38:20
 */
@Service
@Transactional
public class ContractInfoServiceImpl extends AbstractBaseService<ContractInfo> implements ContractInfoService {
	@Autowired
	private ContractReceivableService reServ;
	@Autowired
	private ContractPartitionService staServ;
	
	@Autowired 
	private ContractStationService stationServ;
	
	@Autowired
	private ProjectStationService psServ;
	
	@Autowired
	private ContractInfoMapper ciMapper;
	
	@Autowired
	private SysAttachmentService sysAttachmentService;
	
	@Autowired
	private CustomerTeamService teamServ;
	
	@Autowired
	FinancialSettingService setServ;
	
	@Autowired
	SysMessageService msgServ;
	

	@Override
	@OptLog(module=OptLogConstant.MODULE_CONTRACT,info=OptLogConstant.INFO_ADD)
	public Result insert(ContractInfo record, JSONArray reList, JSONArray staList,String fileId) {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		Date now = new Date();
		//保存应收
		for(int i = 0;i<reList.size();i++){
			JSONObject re=reList.getJSONObject(i);
			ContractReceivable receive = reServ.findById(re.getString("id"));
			receive.setFkDicReceivableType("0");
			receive.setMonthRent(record.getDeposit().divide(new BigDecimal(record.getDepositMonth())));
			receive.setReceivableAmount(re.getBigDecimal("receivableAmount"));
			receive.setStartDate(re.getDate("startDate"));
			receive.setEndDate(re.getDate("endDate"));
			receive.setReceivableDate(re.getDate("receivableDate"));
			if(CorpdataUtil.compare_date(sd.format(receive.getReceivableDate()), sd.format(now))<= 0){
				receive.setReceivableNumber(System.currentTimeMillis()+"");
			}
			receive.setFlag(1);
			reServ.update(receive);
		}
		//保存合同分区关联
		for(int i = 0;i<staList.size();i++){
			JSONObject sta = staList.getJSONObject(i);
			ContractPartition station = staServ.findById(sta.getString("id"));
			station.setRoomPrice(sta.getBigDecimal("roomPrice"));
			station.setStationNumber(sta.getInteger("stationNumber"));
			station.setStationPrice(sta.getBigDecimal("stationPrice"));
			station.setTotalRent(sta.getBigDecimal("stationPrice"));
			station.setFlag(1);
			staServ.update(station);
			//将合同工位关联更新为持久状态
			 stationServ.modifyFlag(record.getId(), station.getPartition().getId());
		}
		//获取系统设置的缴租日
		FinancialSetting set = setServ.findByStatus("6");
		//保存押金
		ContractReceivable yajin =new ContractReceivable();
		yajin.setId(CorpdataUtil.getUUID());
		yajin.setFkDicReceivableType("1");
		yajin.setReceivableDate(now);
		if(set != null){
			if(set.getType().equals("0")){
				yajin.setReceivableDate(CorpdataUtil.getDateFromNow(record.getStartDate(),0, -1));
			}else{
				yajin.setReceivableDate(CorpdataUtil.getDateFromNow(record.getStartDate(),1, -set.getDuration()));
			}
		}else{
			yajin.setReceivableDate(record.getStartDate());
		}
		yajin.setFlag(1);
		yajin.setState(0);
		yajin.setReceivableAmount(record.getDeposit());
		yajin.setContract(record);
		yajin.setCreater(UserUtil.getCurrentUserid());
		yajin.setReceivableDate(now);
		yajin.setReceivableNumber(System.currentTimeMillis()+"");
		yajin.setCreated(now);
		yajin.setModified(now);
		reServ.save(yajin);
		//如果是续签，将原合同押金退款
		if(record.getRenewid() != null && !("").equals(record.getRenewid())){
			reServ.returnYajin(record.getRenewid());
		}
		//如果合同开始日期早于今天，将分区下工位状态设置为已分配，否则设置为已出租
		List<String> idList = stationServ.selectByContract(record.getId());
		if(idList.size() > 0){
			if(CorpdataUtil.compare_date(sd.format(record.getStartDate()),sd.format(now))<=0){
				psServ.updateProjectStation(record.getFkTeam(),"2",idList);//今天开始租用的工位设置为已分配状态
			}else{
				//租期还未开始的工位且工位现在没有合同的设置为已出租状态
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("idList", idList);
				List<ProjectStation> psList = psServ.findAll(params);
				for(ProjectStation ps:psList){
					if(ps.getStationState() == 0){
						ps.setStationState(1);
						ps.setFkCustomerTeam(record.getFkTeam());
						psServ.update(ps);
					}
				}
			}
		}
		record.setState(0);
		if(StringUtils.isBlank(record.getContractNumber())){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssS");
			record.setContractNumber(sdf.format(now));
		}
		//处理附件
		sysAttachmentService.updateDel(fileId,record.getId());
		return super.save(record);
	}

	//终止合同
	@Override
	@OptLog(module=OptLogConstant.MODULE_CONTRACT,info=OptLogConstant.INFO_END)
	public Result endContract(String contractId, JSONArray billList, String delBillStatus, String endDateStatus,
			String endRemark, String realEndDate,String reason) {
		ContractInfo record = super.findById(contractId);
		Date now = new Date();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		//对合同账单操作
		if(delBillStatus.equals("1")){
			for(int i =0;i < billList.size();i++){
				JSONObject re=billList.getJSONObject(i);
				ContractReceivable receive = new ContractReceivable();
				receive.setId(CorpdataUtil.getUUID());
				receive.setFkDicReceivableType("2");//退款状态
				receive.setMonthRent(re.getBigDecimal("price"));
				receive.setReceivableAmount(re.getBigDecimal("price"));
				receive.setStartDate(now);
				receive.setEndDate(now);
				receive.setReceivableDate(now);
				receive.setFlag(1);
				receive.setState(2);//已退款
				receive.setContract(record);
				receive.setReceivableNumber(System.currentTimeMillis()+"");
				receive.setRemark(re.getString("remark"));
				reServ.save(receive);
			}
		}else{
			//合同下所有应收编号去除
			reServ.delContractBill(contractId);
		}
		//合同终止日期合同终止状态操作
		if(endDateStatus.equals("0")){
			realEndDate = sd.format(now);
		}
		if(endDateStatus.equals("0") && realEndDate.compareTo(sd.format(now)) <= 0){
			record.setState(2);
			record.setRealEndDate(CorpdataUtil.getDate(realEndDate));
			psServ.toTuizuStatus(record.getFkTeam());//将工位重置未出租状态
		}else{
			record.setRealEndDate(CorpdataUtil.getDate(realEndDate));
		}
		record.setEndRemark(endRemark);
		record.setDepositType(Integer.parseInt(reason));
		 Result result = super.update(record);
		//查询团队下是否有未结束合同，如果没有则设置为毕业企业
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("teamId", record.getFkTeam());
		 params.put("endState", 2);
		 List<ContractInfo> list = ciMapper.selectAll(params);
		 if(list.size() == 0){
			 CustomerTeam team = teamServ.findById(record.getFkTeam());
			 team.setLesseeState(1);
			 teamServ.update(team);
		 }
		 return result;
	}
	//获取有续签的合同id
	@Override
	public List<String> getReNewIdList() {
		return ciMapper.getReNewIdList();
	}
	//合同到期通知
	@Override
	public Result sendDaoqiMessage() {
		Result result = null;
		Map<String, Object> params = new HashMap<String, Object>();
		// 获取需要发送到期通知的合同
		params.put("state", 0);
		params.put("daoqi", 30);
		List<ContractInfo> list = ciMapper.selectAll(params);
		List<SysMessage> msgList = new ArrayList<SysMessage>();
		List<SysMessageUser> muList = new ArrayList<SysMessageUser>();
		for(ContractInfo ci:list){
			//消息列表添加数据
			msgServ.initList(ci, 2, msgList, muList,-1);
			ci.setState(1);
			ciMapper.update(ci);
			//合同关联的工位设置为快到期
			List<String> idList = stationServ.selectByContract(ci.getId());
			psServ.updateProjectStation(null,"3",idList);
		}
		if(msgList.size() > 0){
			result = msgServ.insertList(msgList,muList);
		}
		return result;
	}
	/**
	 * 验证合同编号是否重复
	 */
	@Override
	public int checkContractNum(String contractNum) {
		return  ciMapper.checkContractNum(contractNum);
	}
	/**
	 * 对自然到期的合同终止
	 */
	@Override
	public void terminationContract() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("endState", 2);
		params.put("termination", 1);
		List<ContractInfo> list = ciMapper.selectAll(params );
		for(ContractInfo record:list){
			record.setState(2);
			super.update(record);
			psServ.toTuizuStatus(record.getFkTeam());//将工位重置未出租状态
			//查询团队下是否有未结束合同，如果没有则设置为毕业企业
			 Map<String, Object> param = new HashMap<String, Object>();
			 params.put("teamId", record.getFkTeam());
			 params.put("endState", 2);
			 List<ContractInfo> ciList = ciMapper.selectAll(param);
			 if(ciList.size() == 0){
				 CustomerTeam team = teamServ.findById(record.getFkTeam());
				 team.setLesseeState(1);
				 teamServ.update(team);
			 }
		}
	}
	/**
	 * 对今天开始的合同关联工位处理
	 */
	@Override
	public void startContract() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("endState", 2);
		params.put("newStartDate", 1);
		List<ContractInfo> list = ciMapper.selectAll(params );
		for(ContractInfo record:list){
			//将分区下工位状态设置为已出租
			List<String> idList = stationServ.selectByContract(record.getId());
			psServ.updateProjectStation(record.getFkTeam(),"2",idList);
		}
	}
	/**
	 * 删除合同相关的临时数据
	 */
	@Override
	public void delTemporaryData() {
		//删除临时应收
		reServ.delTemporaryReceive();
		//删除临时分区合同关联
		staServ.delTemporaryData();
		//删除临时工位合同关联
		stationServ.delTemporaryData();
	}
	//获取合同到期天数
	@Override
	public int getDaoQiDays(String fkTeam) {
		Integer days = ciMapper.getDaoQiDays(fkTeam);
		if(days == null){
			return 0;
		}else{
			return days;
		}
	}
	
	
}
